package com.ruoyi.crm.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.crm.domain.CompanySize;
import com.ruoyi.crm.domain.CustomerInfo;
import com.ruoyi.crm.domain.PoolCustomer;
import com.ruoyi.crm.mapper.CompanySizeMapper;
import com.ruoyi.crm.mapper.CustomerMapper;
import com.ruoyi.crm.mapper.PoolCustomerMapper;
import com.ruoyi.crm.service.IPoolCustomerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@RequiredArgsConstructor
@Service
public class PoolCustomerServiceImpl implements IPoolCustomerService {
    private final PoolCustomerMapper poolCustomerMapper;
    private final CustomerMapper customerMapper;
    private final CompanySizeMapper companySizeMapper;
    /**
     * 查询公海客户
     * @param poolCustomer
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<PoolCustomer> selectPoolCustomerPageList(PoolCustomer poolCustomer, PageQuery pageQuery) {
        Map<String, Object> params = poolCustomer.getParams();
        LambdaQueryWrapper<PoolCustomer> lqw = new LambdaQueryWrapper<>();

        // 模糊查询 customer_name => 关联 customer_info 表中的 customer_id
        if (poolCustomer.getCustomerId() != null && StringUtils.isNotBlank(poolCustomer.getCustomerId().toString())) {
            lqw.inSql(PoolCustomer::getCustomerId,
                "SELECT customer_id FROM crm_customer_info WHERE customer_name LIKE '%" + poolCustomer.getCustomerId() + "%'");
        }

        // 模糊查询 company_size_name => 关联 company_size 表中的 company_size_id
        if (poolCustomer.getCompanySizeId() != null && StringUtils.isNotBlank(poolCustomer.getCompanySizeId().toString())) {
            lqw.inSql(PoolCustomer::getCompanySizeId,
                "SELECT company_size_id FROM crm_company_size WHERE company_size_name LIKE '%" + poolCustomer.getCompanySizeId() + "%'");
        }

        // 精确匹配负责人ID
        lqw.eq(poolCustomer.getResponsiblePersonId() != null,
            PoolCustomer::getResponsiblePersonId, poolCustomer.getResponsiblePersonId());

        // 精确匹配客户类型ID
        lqw.eq(poolCustomer.getCustomerTypeId() != null,
            PoolCustomer::getCustomerTypeId, poolCustomer.getCustomerTypeId());

        // 时间范围过滤
        if (params.get("beginTime") != null && params.get("endTime") != null) {
            lqw.between(PoolCustomer::getNextTime, params.get("beginTime"), params.get("endTime"));
        }

        // 排序
        lqw.orderByAsc(PoolCustomer::getNextTime);

        Page<PoolCustomer> page = poolCustomerMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

//    @Override
//    public TableDataInfo<PoolCustomer> selectPoolCustomerPageList(PoolCustomer poolCustomer, PageQuery pageQuery) {
//        Map<String, Object> params = poolCustomer.getParams();
//        LambdaQueryWrapper<PoolCustomer> lqw = new LambdaQueryWrapper<PoolCustomer>()
//            .inSql(PoolCustomer::getCustomerId,"select customer_id from customer_info where customer_name like '%"+poolCustomer.getCustomerId()+"%'")
//            .or()
//            .inSql(PoolCustomer::getCompanySizeId,"select company_size_id from company_size where company_size_name like '%"+poolCustomer.getCompanySizeId()+"%'")
//            .or()
//            .eq(poolCustomer.getResponsiblePersonId() != null, PoolCustomer::getResponsiblePersonId,poolCustomer.getResponsiblePersonId())
//            .or()
//            .eq(poolCustomer.getCustomerTypeId() != null, PoolCustomer::getCustomerTypeId,poolCustomer.getCustomerTypeId())
//            .between(params.get("beginTime") != null && params.get("endTime") != null,
//                PoolCustomer::getNextTime,  // 使用Lambda方法引用
//                params.get("beginTime"),
//                params.get("endTime"))
//            .orderByAsc(PoolCustomer::getNextTime);
//        Page<PoolCustomer> page = poolCustomerMapper.selectPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(page);
//    }

    /**
     * 修改公海客户
     * @param poolCustomer
     * @return
     */

    @Override
    public int updatePoolCustomerById(PoolCustomer poolCustomer) {
        return poolCustomerMapper.updateById(poolCustomer);
    }

    /**
     * 删除公海客户
     * @param poolId
     * @return
     */

    @Override
    public int deletePoolCustomerById(Long poolId) {
        return poolCustomerMapper.deleteById(poolId);
    }

    /**
     * 查询公海客户列表
     * @param poolCustomer
     * @return
     */
//   @Override
// public List<PoolCustomer> selectPoolCustomerList(PoolCustomer poolCustomer) {
//     Map<String, Object> params = poolCustomer.getParams();
//    return poolCustomerMapper.selectList(new LambdaQueryWrapper<PoolCustomer>()
////            .inSql(PoolCustomer::getCustomerId,"select customer_id from customer_info where customer_name like '%"+poolCustomer.getCustomerId()+"%'")
////            .or()
////            .inSql(PoolCustomer::getCompanySizeId,"select company_size_id from company_size where company_size_name like '%"+poolCustomer.getCompanySizeId()+"%'")
////            .or()
////            .eq(poolCustomer.getResponsiblePersonId() != null, PoolCustomer::getResponsiblePersonId,poolCustomer.getResponsiblePersonId())
////            .or()
////            .eq(poolCustomer.getCustomerTypeId() != null, PoolCustomer::getCustomerTypeId,poolCustomer.getCustomerTypeId())
////            .between(params.get("beginTime") != null && params.get("endTime") != null,
////                PoolCustomer::getNextTime,  // 使用Lambda方法引用
////                params.get("beginTime"),
////                params.get("endTime"))
////            .orderByAsc(PoolCustomer::getNextTime)
////        );
//   }
    @Override
    public List<PoolCustomer> selectPoolCustomerList(PoolCustomer poolCustomer) {
        Map<String, Object> params = poolCustomer.getParams();
        LambdaQueryWrapper<PoolCustomer> wrapper = new LambdaQueryWrapper<>();

        // 模糊查 customer_name -> customer_id
        if (StrUtil.isNotBlank(String.valueOf(poolCustomer.getCustomerId()))) {
            List<Long> customerIdList = customerMapper.selectList(
                new LambdaQueryWrapper<CustomerInfo>()
                    .like(CustomerInfo::getCustomerName, poolCustomer.getCustomerId())
            ).stream().map(CustomerInfo::getCustomerId).collect(Collectors.toList());

            if (!customerIdList.isEmpty()) {
                wrapper.in(PoolCustomer::getCustomerId, customerIdList);
            }
        }

         /**模糊查 company_size_name -> company_size_id*/
        if (StrUtil.isNotBlank(String.valueOf(poolCustomer.getCompanySizeId()))) {
            List<Long> companySizeIdList = companySizeMapper.selectList(
                new LambdaQueryWrapper<CompanySize>()
                    .like(CompanySize::getCompanySizeName, poolCustomer.getCompanySizeId())
            ).stream().map(CompanySize::getCompanySizeId).collect(Collectors.toList());

            if (!companySizeIdList.isEmpty()) {
                wrapper.in(PoolCustomer::getCompanySizeId, companySizeIdList);
            }
        }

        if (poolCustomer.getResponsiblePersonId() != null) {
            wrapper.eq(PoolCustomer::getResponsiblePersonId, poolCustomer.getResponsiblePersonId());
        }

        if (poolCustomer.getCustomerTypeId() != null) {
            wrapper.eq(PoolCustomer::getCustomerTypeId, poolCustomer.getCustomerTypeId());
        }

        if (params != null && params.get("beginTime") != null && params.get("endTime") != null) {
            wrapper.between(PoolCustomer::getNextTime, params.get("beginTime"), params.get("endTime"));
        }

        wrapper.orderByAsc(PoolCustomer::getNextTime);

        return poolCustomerMapper.selectList(wrapper);
    }
    /**
     * 批量新增
     */
    @Override
    public boolean insertBatch(List<PoolCustomer> list) {
        return poolCustomerMapper.insertBatch(list);
    }

}
